package org.snail.core;

import org.snail.serialization.SerializerFactory;
import org.snail.transport.protocol.Message;
import org.snail.transport.protocol.Request;
import org.snail.transport.protocol.Response;
import org.snail.transport.protocol.StatusType;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * Created by fish on 17/4/7.
 */
public class InvokeFuture{

    private CountDownLatch latch = new CountDownLatch(1);

    private Object value;

    private Request request;

    private Class<?> returnType;

    private final long startTime = System.nanoTime();

    private volatile Message responseMessage;


    public boolean cancel() {
        if(this.latch.getCount() == 1){
            this.latch.countDown();
            return true;
        }
        return false;
    }


    public boolean isDone() {
        return latch.getCount() == 0;
    }


    public Object getValue(long time)  {
        if(value == null){
            try {
                latch.await(time, TimeUnit.MILLISECONDS);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            Response response = SerializerFactory.getDefaultSerializer().readObject(responseMessage.getBody(), Response.class);
            value = response.getResult();
        }
        return value;
    }


    public void receive(Message message){
        this.responseMessage = message;
        if(latch.getCount() == 1){
            this.latch.countDown();
        }
    }

    public Class<?> getReturnType() {
        return returnType;
    }

    public void setReturnType(Class<?> returnType) {
        this.returnType = returnType;
    }
}
